<template>
	<view class="luxury-category-container">
		<!-- 背景图片 -->
		<image :src="pageImages.category_background" class="background-image" mode="aspectFill"></image>

		<!-- 渐变遮罩 -->
		<view class="background-overlay"></view>

		<!-- 商品列表区域 -->
		<view class="products-section" v-if="!loading && currentProducts.length > 0">
			<!-- 装饰性背景图片 -->
			<image :src="pageImages.category_decoration" class="products-bg-decoration" mode="aspectFill"></image>

			<view class="products-header">
				<text class="section-title" v-if="currentCategory">{{ currentCategory.name }}</text>
				<text class="section-subtitle" v-if="currentCategory">{{ getCategorySubtitle(currentCategory.name) }}</text>
				<view class="products-count" v-if="totalCount > 0">
					<text class="count-text">共 {{ totalCount }} 件商品</text>
				</view>
			</view>

			<view class="product-grid">
				<view class="product-item" v-for="item in currentProducts" :key="item.id" @click="goToProductDetail(item)">
					<image :src="item.main_image_url || '/static/icons/08ff0bd53a8643cd360e68f761bc2c25.jpg'" class="product-image" mode="aspectFill"></image>
					<view class="product-info">
						<text class="product-name">{{ item.name }}</text>
						<text class="product-price">¥{{ item.price }}</text>
					</view>
				</view>
			</view>

			<!-- 分页导航区域 -->
			<view class="pagination-area" v-if="totalPages > 1">
				<view class="pagination-container">
					<!-- 上一页按钮 -->
					<view
						class="pagination-btn prev-btn"
						:class="{ disabled: currentPage <= 1 }"
						@click="goToPage(currentPage - 1)"
					>
						<text class="btn-text">上一页</text>
					</view>

					<!-- 页码列表 -->
					<view class="page-numbers">
						<!-- 第一页 -->
						<view
							v-if="showFirstPage"
							class="page-number"
							:class="{ active: currentPage === 1 }"
							@click="goToPage(1)"
						>
							<text class="page-text">1</text>
						</view>

						<!-- 省略号（前） -->
						<view v-if="showStartEllipsis" class="ellipsis">
							<text class="ellipsis-text">...</text>
						</view>

						<!-- 中间页码 -->
						<view
							v-for="page in visiblePages"
							:key="page"
							class="page-number"
							:class="{ active: currentPage === page }"
							@click="goToPage(page)"
						>
							<text class="page-text">{{ page }}</text>
						</view>

						<!-- 省略号（后） -->
						<view v-if="showEndEllipsis" class="ellipsis">
							<text class="ellipsis-text">...</text>
						</view>

						<!-- 最后一页 -->
						<view
							v-if="showLastPage"
							class="page-number"
							:class="{ active: currentPage === totalPages }"
							@click="goToPage(totalPages)"
						>
							<text class="page-text">{{ totalPages }}</text>
						</view>
					</view>

					<!-- 下一页按钮 -->
					<view
						class="pagination-btn next-btn"
						:class="{ disabled: currentPage >= totalPages }"
						@click="goToPage(currentPage + 1)"
					>
						<text class="btn-text">下一页</text>
					</view>
				</view>

				<!-- 分页信息 -->
				<view class="pagination-info">
					<text class="info-text">第 {{ currentPage }} 页，共 {{ totalPages }} 页，{{ totalCount }} 件商品</text>
				</view>
			</view>
		</view>

		<!-- 加载中状态 -->
		<view v-if="loading" class="loading-container">
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 空状态 -->
		<view v-else-if="currentProducts.length === 0" class="empty-container">
			<text class="empty-text">暂无商品</text>
		</view>

		<!-- 分类导航 -->
		<view class="category-navigation">
			<view class="nav-container">
				<view
					class="nav-category"
					v-for="category in categoryList"
					:key="category.id"
					:class="{ active: activeCategory === category.id }"
					@click="switchCategory(category.id)"
				>
					<image :src="getCategoryIcon(category.name)" class="category-icon" mode="aspectFit"></image>
					<text class="category-name">{{ category.name }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { get, showLoading, hideLoading, showError } from '@/utils/request.js'
import { processProductsImages, convertToHttpsImageUrl } from '@/utils/imageUtils.js'
import { getPageImages, getCategoryIconUrl } from '@/utils/imageConfig.js'

export default {
	data() {
		return {
			// 页面图片配置
			pageImages: {
				category_background: '/static/background.jpg',
				category_decoration: '/static/icons/82b7bbcbef19ede7b9f139d6068994ce.jpg'
			},
			searchKeyword: '',
			activeCategory: 1,
			loading: false,
			// 主打产品配置
			featuredProducts: {
				'婚礼系列': {
					title: '永恒之约',
					subtitle: '见证爱情的永恒时刻',
					image: '/static/icons/0.jpg'
				},
				'通勤系列': {
					title: '优雅职场',
					subtitle: '精致生活，优雅职场',
					image: '/static/icons/08ff0bd53a8643cd360e68f761bc2c25.jpg'
				},
				'个性系列': {
					title: '独特魅力',
					subtitle: '展现独特的你',
					image: '/static/icons/09.webp'
				},
				'定制系列': {
					title: '专属定制',
					subtitle: '专属于你的独一无二',
					image: '/static/icons/3.jpg'
				},
				'默认': {
					title: 'Luxury Collection',
					subtitle: '精致优雅，时光见证',
					image: '/static/icons/08ff0bd53a8643cd360e68f761bc2c25.jpg'
				}
			},
			// 珠宝图片映射（为后端分类分配图片）
			categoryImageMap: {
				'戒圈戒指': '/static/classes/1.jpg',
				'吊坠项链': '/static/classes/2.jpg',
				'耳饰': '/static/classes/3.jpg',
				'手镯手链': '/static/classes/4.png',
				'星钻': '/static/classes/5.jpg',
			},
			// 分类图标缓存（动态加载）
			categoryIconCache: {},
			// 分类列表
			categoryList: [],
			// 当前商品列表
			currentProducts: [],
			// 分页信息
			currentPage: 1,
			pageSize: 6,
			totalCount: 0,
			totalPages: 0,
			// 搜索防抖定时器
			searchTimer: null,
			// 刷新状态
			isRefreshing: false
		}
	},
	computed: {
		// 当前选中的分类对象
		currentCategory() {
			return this.categoryList.find(cat => cat.id === this.activeCategory)
		},

		// 当前主打产品
		featuredProduct() {
			// 如果有商品数据，使用第一个商品作为主打产品
			if (this.currentProducts.length > 0) {
				const firstProduct = this.currentProducts[0];
				return {
					title: firstProduct.name,
					subtitle: this.getCategorySubtitle(this.currentCategory?.name || ''),
					image: convertToHttpsImageUrl(firstProduct.main_image_url) || '/static/icons/08ff0bd53a8643cd360e68f761bc2c25.jpg'
				};
			}

			// 否则使用配置的默认产品
			const categoryName = this.currentCategory?.name || '默认';
			return this.featuredProducts[categoryName] || this.featuredProducts['默认'];
		},

		// 分页相关计算属性
		// 可见的页码列表
		visiblePages() {
			const pages = [];
			const maxVisible = 5; // 最多显示5个页码
			const half = Math.floor(maxVisible / 2);

			let start = Math.max(1, this.currentPage - half);
			let end = Math.min(this.totalPages, start + maxVisible - 1);

			// 调整起始位置，确保显示足够的页码
			if (end - start + 1 < maxVisible) {
				start = Math.max(1, end - maxVisible + 1);
			}

			// 排除第一页和最后一页（它们单独显示）
			for (let i = start; i <= end; i++) {
				if (i !== 1 && i !== this.totalPages) {
					pages.push(i);
				} else if (this.totalPages <= maxVisible) {
					// 如果总页数很少，显示所有页码
					pages.push(i);
				}
			}

			return pages;
		},

		// 是否显示第一页
		showFirstPage() {
			return this.totalPages > 1 && (this.visiblePages.length === 0 || this.visiblePages[0] > 1);
		},

		// 是否显示最后一页
		showLastPage() {
			return this.totalPages > 1 && (this.visiblePages.length === 0 || this.visiblePages[this.visiblePages.length - 1] < this.totalPages);
		},

		// 是否显示开始省略号
		showStartEllipsis() {
			return this.showFirstPage && this.visiblePages.length > 0 && this.visiblePages[0] > 2;
		},

		// 是否显示结束省略号
		showEndEllipsis() {
			return this.showLastPage && this.visiblePages.length > 0 && this.visiblePages[this.visiblePages.length - 1] < this.totalPages - 1;
		}
	},
	async onLoad() {
		await this.loadPageImages();
		this.loadCategories();
		
		// 显示分享菜单
		// #ifdef MP-WEIXIN
		wx.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		});
		// #endif
	},

	// 下拉刷新
	onPullDownRefresh() {
		this.refreshProducts().then(() => {
			uni.stopPullDownRefresh();
		});
	},


	methods: {
		// 加载页面图片配置
		async loadPageImages() {
			try {
				const images = await getPageImages('category');

				if (images.category_background) {
					this.pageImages.category_background = images.category_background.url;
				}
				if (images.category_decoration) {
					this.pageImages.category_decoration = images.category_decoration.url;
				}

				console.log('分类页面图片配置加载完成');
			} catch (error) {
				console.warn('加载页面图片配置失败，使用默认图片:', error);
			}
		},

		// 加载分类列表
		async loadCategories() {
			try {
				showLoading('加载中...');
				const res = await get('/public/categories/top');
				console.log('分类列表响应:', res);
				this.categoryList = res.data || [];
				console.log('获取到的分类:', this.categoryList);

				// 预加载所有分类图标
				await this.preloadCategoryIcons();

				// 默认选中第一个分类
				if (this.categoryList.length > 0) {
					this.activeCategory = this.categoryList[0].id;
					console.log('选中的分类ID:', this.activeCategory);
					await this.loadProducts();
				}
			} catch (error) {
				console.error('加载分类失败:', error);
				showError('加载分类失败');
			} finally {
				hideLoading();
			}
		},

		// 预加载所有分类图标
		async preloadCategoryIcons() {
			try {
				for (const category of this.categoryList) {
					try {
						const iconUrl = await getCategoryIconUrl(category.name);
						this.categoryIconCache[category.name] = iconUrl;
					} catch (error) {
						console.error(`预加载分类图标失败: ${category.name}`, error);
						// 设置默认图标
						this.categoryIconCache[category.name] = '/static/icons/08ff0bd53a8643cd360e68f761bc2c25.jpg';
					}
				}
				console.log('分类图标预加载完成');
			} catch (error) {
				console.error('预加载分类图标失败:', error);
			}
		},

		// 加载商品列表
		async loadProducts(page = 1) {
			if (this.loading) return;

			try {
				this.loading = true;

				const params = {
					category_id: this.activeCategory, // 使用 category_id 精确匹配分类
					page,
					pageSize: this.pageSize
				};

				console.log('请求商品列表参数:', params);

				// 添加搜索关键词
				if (this.searchKeyword.trim()) {
					params.search = this.searchKeyword.trim();
				}

				const res = await get('/public/products', params);
				console.log('商品列表响应:', res);

				// 根据后端API响应格式解析数据
				let products = [];
				let total = 0;

				if (res.data && res.data.products) {
					// 如果响应格式是 { data: { products: [], total: 0 } }
					products = res.data.products || [];
					total = res.data.total || 0;
				} else if (res.data && Array.isArray(res.data)) {
					// 如果响应格式是 { data: [] }
					products = res.data;
					// 如果后端没有实现分页，估算总数
					if (page === 1 && products.length === this.pageSize) {
						// 第一页满了，估算可能有更多页
						total = products.length * 2; // 保守估计
					} else {
						total = (page - 1) * this.pageSize + products.length;
					}
				} else {
					// 其他格式
					products = [];
					total = 0;
				}

				console.log('解析后的商品数量:', products.length, '总数:', total);

				// 处理商品图片URL，转换为HTTPS地址
				const processedProducts = processProductsImages(products);
				console.log('图片URL处理完成');

				// 更新商品列表和分页信息
				this.currentProducts = processedProducts;
				this.currentPage = page;
				this.totalCount = total;
				this.totalPages = Math.ceil(total / this.pageSize);

				// 如果当前页返回的商品数量小于pageSize，说明这是最后一页，更新总数
				if (products.length < this.pageSize && page > 1) {
					this.totalCount = (page - 1) * this.pageSize + products.length;
					this.totalPages = page;
				}

				console.log('分页状态 - 当前页:', this.currentPage, '总页数:', this.totalPages, '总商品数:', this.totalCount);

			} catch (error) {
				console.error('加载商品失败:', error);
				showError('加载商品失败');
			} finally {
				this.loading = false;
			}
		},

		// 切换分类
		async switchCategory(categoryId) {
			if (this.activeCategory === categoryId) return;

			this.activeCategory = categoryId;
			await this.loadProducts(1); // 重新加载第一页
		},

		// 搜索输入
		onSearchInput() {
			// 清除之前的定时器
			if (this.searchTimer) {
				clearTimeout(this.searchTimer);
			}

			// 设置防抖，500ms后执行搜索
			this.searchTimer = setTimeout(() => {
				this.loadProducts(1); // 搜索时回到第一页
			}, 500);
		},

		// 跳转到指定页面
		async goToPage(page) {
			if (page < 1 || page > this.totalPages || page === this.currentPage) {
				return;
			}

			await this.loadProducts(page);
		},

		// 跳转到产品详情
		goToProductDetail(product) {
			uni.navigateTo({
				url: `/pages/product/detail?id=${product.id}`
			});
		},

		// 获取分类副标题
		getCategorySubtitle(categoryName) {
			const subtitles = {
				'婚礼系列': '见证爱情的永恒时刻',
				'通勤系列': '优雅职场，精致生活',
				'个性系列': '展现独特的你',
				'定制系列': '专属于你的独一无二'
			};
			return subtitles[categoryName] || '精美珠宝，品质之选';
		},

		// 获取分类图标
		getCategoryIcon(categoryName) {
			// 优先从缓存中获取动态配置的图标
			if (this.categoryIconCache[categoryName]) {
				return this.categoryIconCache[categoryName];
			}
			// 如果缓存中没有，使用硬编码映射作为后备
			return this.categoryImageMap[categoryName] || '/static/icons/08ff0bd53a8643cd360e68f761bc2c25.jpg';
		},

		// 手动刷新
		async refreshProducts() {
			if (this.isRefreshing) return;

			this.isRefreshing = true;
			await this.loadProducts(1); // 刷新时回到第一页
			this.isRefreshing = false;
		}
	},

	// 分享功能
	onShareAppMessage() {
		const categoryName = this.currentCategory?.name || '分类';
		const categoryImage = this.pageImages.category_decoration || this.pageImages.category_background || '';
		
		return {
			title: `${categoryName} - 精美珠宝品质之选`,
			path: `/pages/category/category?categoryId=${this.activeCategory}`,
			imageUrl: categoryImage
		}
	},

	onShareTimeline() {
		const categoryName = this.currentCategory?.name || '分类';
		const categoryImage = this.pageImages.category_decoration || this.pageImages.category_background || '';
		
		return {
			title: `${categoryName} - 精美珠宝品质之选`,
			query: `categoryId=${this.activeCategory}`,
			imageUrl: categoryImage
		}
	}
}
</script>

<style scoped>
.luxury-category-container {
	min-height: 100vh;
	position: relative;
	background: #f5f1e8;
}

/* 背景图片 */
.background-image {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100vh;
	z-index: 1;
}

.background-overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100vh;
	background: linear-gradient(
		180deg,
		rgba(245, 241, 232, 0.4) 0%,
		rgba(232, 220, 198, 0.7) 50%,
		rgba(215, 195, 165, 0.9) 100%
	);
	z-index: 2;
}

/* 分类导航 */
.category-navigation {
	position: fixed;
	bottom: 0rpx; /* 在系统导航栏上方 */
	left: 0;
	right: 0;
	z-index: 10;
	background: rgba(44, 44, 44, 0.9);
	backdrop-filter: blur(20rpx);
	padding: 20rpx 0;
	border-radius: 40rpx 40rpx 0 0;
}

.nav-container {
	display: flex;
	justify-content: space-around;
	align-items: center;
	padding: 0 20rpx;
}

.nav-category {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8rpx;
	transition: all 0.3s ease;
	opacity: 0.7;
}

.nav-category.active {
	opacity: 1;
	transform: scale(1.05);
}

.category-icon {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	border: 2rpx solid rgba(255, 255, 255, 0.3);
	transition: all 0.3s ease;
}

.nav-category.active .category-icon {
	border-color: #D4AF37;
	box-shadow: 0 0 15rpx rgba(212, 175, 55, 0.5);
}

.category-name {
	font-size: 20rpx;
	color: #ffffff;
	font-weight: 300;
	letter-spacing: 1rpx;
}

/* 商品列表区域 */
.products-section {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(20rpx);
	border-radius: 0 0 40rpx 40rpx;
	margin: 0;
	padding: 40rpx 40rpx 280rpx; /* 为底部分类导航和系统导航栏留出空间 */
	position: relative;
	z-index: 5;
	margin-top: 0;
	overflow: hidden;
}

/* 商品区域装饰背景 */
.products-bg-decoration {
	position: absolute;
	top: -100rpx;
	right: -100rpx;
	width: 400rpx;
	height: 400rpx;
	opacity: 0.05;
	z-index: 1;
	transform: rotate(15deg);
}

.products-header {
	text-align: center;
	margin-bottom: 60rpx;
}

.section-title {
	font-size: 48rpx;
	font-weight: 300;
	color: #2c2c2c;
	display: block;
	margin-bottom: 20rpx;
	letter-spacing: 2rpx;
}

.section-subtitle {
	font-size: 28rpx;
	color: #666666;
	font-weight: 300;
}

.products-count {
	margin-top: 20rpx;
}

.count-text {
	font-size: 24rpx;
	color: #999999;
	font-weight: 300;
}

/* 产品网格 */
.product-grid {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 30rpx;
	margin-bottom: 80rpx; /* 增加底部间距，确保最后一行商品不被遮挡 */
}

.product-item {
	background: linear-gradient(135deg,
		rgba(255, 255, 255, 0.95) 0%,
		rgba(255, 255, 255, 0.9) 100%);
	border-radius: 20rpx;
	overflow: hidden;
	box-shadow: 0 8rpx 32rpx rgba(212, 175, 55, 0.15);
	transition: all 0.3s ease;
	backdrop-filter: blur(10rpx);
	border: 1rpx solid rgba(212, 175, 55, 0.1);
	position: relative;
}

.product-item:hover {
	transform: translateY(-8rpx);
	box-shadow: 0 16rpx 48rpx rgba(0, 0, 0, 0.15);
}

.product-image {
	width: 100%;
	height: 300rpx;
}

.product-info {
	padding: 30rpx;
	text-align: center;
}

.product-name {
	font-size: 28rpx;
	color: #2c2c2c;
	font-weight: 500;
	display: block;
	margin-bottom: 15rpx;
	line-height: 1.4;
}

.product-price {
	font-size: 32rpx;
	color: #D4AF37;
	font-weight: 600;
}

/* 分页区域 */
.pagination-area {
	position: fixed;
	bottom: 220rpx; /* 在分类导航上方 */
	left: 0;
	right: 0;
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(20rpx);
	padding: 15rpx 0;
	text-align: center;
	z-index: 8;
	border-top: 1rpx solid rgba(0, 0, 0, 0.1);
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.pagination-container {
	display: flex;
	justify-content: center;
	align-items: center;
	gap: 15rpx;
	margin-bottom: 15rpx;
	flex-wrap: wrap;
}

/* 分页按钮 */
.pagination-btn {
	padding: 12rpx 24rpx;
	border-radius: 20rpx;
	border: 1rpx solid #D4AF37;
	background: rgba(255, 255, 255, 0.9);
	transition: all 0.3s ease;
}

.pagination-btn.disabled {
	opacity: 0.4;
	border-color: #cccccc;
}

.pagination-btn:not(.disabled):active {
	background: #D4AF37;
	transform: scale(0.95);
}

.pagination-btn:not(.disabled):active .btn-text {
	color: #ffffff;
}

.btn-text {
	font-size: 22rpx;
	color: #D4AF37;
	font-weight: 500;
	transition: color 0.3s ease;
}

.pagination-btn.disabled .btn-text {
	color: #cccccc;
}

/* 页码列表 */
.page-numbers {
	display: flex;
	align-items: center;
	gap: 12rpx;
	flex-wrap: wrap;
}

/* 页码按钮 */
.page-number {
	width: 50rpx;
	height: 50rpx;
	border-radius: 50%;
	border: 1rpx solid #D4AF37;
	background: rgba(255, 255, 255, 0.9);
	display: flex;
	justify-content: center;
	align-items: center;
	transition: all 0.3s ease;
}

.page-number.active {
	background: #D4AF37;
	box-shadow: 0 4rpx 12rpx rgba(212, 175, 55, 0.3);
}

.page-number:not(.active):active {
	transform: scale(0.9);
	background: rgba(212, 175, 55, 0.1);
}

.page-text {
	font-size: 22rpx;
	color: #D4AF37;
	font-weight: 500;
}

.page-number.active .page-text {
	color: #ffffff;
}

/* 省略号 */
.ellipsis {
	padding: 0 8rpx;
}

.ellipsis-text {
	font-size: 22rpx;
	color: #999999;
	font-weight: 500;
}

/* 分页信息 */
.pagination-info {
	margin-top: 20rpx;
}

.info-text {
	font-size: 20rpx;
	color: #666666;
	font-weight: 300;
}

/* 加载和空状态 */
.loading-container,
.empty-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 100rpx 40rpx 280rpx; /* 为底部分类导航和系统导航栏留出空间 */
	background: rgba(255, 255, 255, 0.9);
	backdrop-filter: blur(20rpx);
	border-radius: 0 0 40rpx 40rpx;
	margin: 0;
	position: relative;
	z-index: 5;
}

.loading-text,
.empty-text {
	font-size: 28rpx;
	color: #666666;
	font-weight: 300;
}



/* 响应式设计 */
@media screen and (max-width: 750rpx) {
	.featured-image {
		width: 400rpx;
		height: 400rpx;
	}

	.product-title {
		font-size: 48rpx;
	}

	.brand-name {
		font-size: 40rpx;
	}

	.nav-container {
		padding: 0 15rpx;
	}

	.category-icon {
		width: 50rpx;
		height: 50rpx;
	}

	.category-name {
		font-size: 18rpx;
	}

	.pagination-area {
		bottom: 120rpx; /* 小屏幕上更靠下 */
	}

	.pagination-container {
		gap: 10rpx;
	}

	.pagination-btn {
		padding: 10rpx 20rpx;
	}

	.btn-text {
		font-size: 20rpx;
	}

	.page-number {
		width: 45rpx;
		height: 45rpx;
	}

	.page-text {
		font-size: 20rpx;
	}

	.info-text {
		font-size: 18rpx;
	}
}

/* 过渡动画 - 微信小程序不支持通用选择器，已移除 */
</style>
